<template>
    <div class="eUpload">
        <a-upload
                name="图片"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :action="apiUrl+'common/upload'"
                :before-upload="beforeUpload"
                @change="handleChange"
                accept=".png,.jpg"
            >
            <img v-if="imageUrl" :src="imageUrl" />
            <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                    上传
                </div>
            </div>
        </a-upload>
        <div class="warning">
            <p>图片最佳尺寸{{size}}</p>
            <p>支持jpg/png格式的图片</p>
            <p>图片大小小于2M</p>
        </div>
    </div>
</template>
<script>
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
    name:'eUpload',
    props:{
        imageUrl:String,
        size:{
            type:String,
            default:"600*260"
        }
    },
    data(){
        return{
            loading: false,
            apiUrl:window.g.apiUrl
        }
    },
    methods: {
        handleChange(info) {
        if (info.file.status === 'uploading') {
            this.loading = true;
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, imageUrl => {
            imageUrl = imageUrl;
            this.loading = false;
            this.$emit('getUrl',info.file.response.data.imgUrl[0])
            });
        }
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('支持jpg/png格式的图片');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('图片大小小于2M');
            }
            return isJpgOrPng && isLt2M;
        },
    }
}
</script>
<style scoped lang="stylus">
.eUpload
    display:flex
    .warning
        p
            margin:0;
            line-height:32px;
            color:red
    img 
        max-height:104px;
</style>